<template>
  <div class="app">
    <StagewiseToolbar v-if="isDev" :config="{ plugins: [VuePlugin] }" />
    <!-- 添加调试信息显示区域，仅在开发环境显示 -->
    <!-- <div v-if="isDev" class="debug-panel">
      <h3>调试信息</h3>
      <p>当前语言: {{ currentLang }}</p>
      <p>可用语言: {{ availableLanguagesList }}</p>
      <p>URL语言参数: {{ urlLang }}</p>
      <div class="debug-buttons">
        <button @click="changeLang('zh')">切换到中文</button>
        <button @click="changeLang('en')">切换到英文</button>
        <button @click="changeLang('es')">切换到西班牙文</button>
        <button @click="changeLang('fr')">切换到法文</button>
      </div>
    </div> -->

    <!-- 语言切换按钮 -->
    <!-- <div class="language-switcher" v-if="showLanguageSwitcher">
			<div class="language-title">
				{{ t('language') || '选择语言/Language' }}
			</div>
			<div class="language-buttons">
				<button
					v-for="lang in availableLanguagesForSwitcher"
					:key="lang.code"
					@click="changeLanguage(lang.code)"
					:class="{ active: currentLang === lang.code }"
				>
					{{ lang.name }}
				</button>
			</div>
		</div> -->

    <router-view v-slot="{ Component }">
      <transition name="fade" mode="out-in">
        <component :is="Component" />
      </transition>
    </router-view>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { computed, onMounted, ref, watch } from 'vue'
import { setLocale, getSupportedLocales } from './i18n'
import { debugTranslation } from './i18n-debug'
import { useOrderStore } from '@/stores/order'
import { getOrderDetailApi } from '@/api/user'
import { StagewiseToolbar } from '@stagewise/toolbar-vue'
import { VuePlugin } from '@stagewise-plugins/vue'

const orderStore = useOrderStore()
// 通过ref定义环境变量
const isDev = ref(import.meta.env.DEV)

const route = useRoute()
// 使用useI18n获取本地i18n实例，用于显示
const { t, locale: currentLocale } = useI18n()
const currentLang = computed(() => currentLocale.value)
const availableLanguages = ref(getSupportedLocales())
const availableLanguagesList = computed(() =>
  availableLanguages.value.join(', ')
)

const urlLang = ref('未检测')

// 显示语言切换器的状态
const showLanguageSwitcher = ref(true)

// 可用语言列表 (用于切换器界面)
const availableLanguagesForSwitcher = [
  { code: 'zh', name: '中文' },
  { code: 'en', name: 'English' },
  { code: 'es', name: 'Español' },
  { code: 'fr', name: 'Français' },
]

// 获取URL中的语言参数
function getUrlLanguage() {
  try {
    const urlParams = new URLSearchParams(window.location.search)
    urlLang.value = urlParams.get('lang') || '未设置'
    const lang = urlParams.get('lang')
    if (lang && availableLanguages.value.includes(lang)) {
      console.log('从URL中检测到语言参数:', lang)
      // 使用全局函数设置语言
      setLocale(lang)
    }
  } catch (error) {
    console.error('解析URL语言参数出错:', error)
  }
}

// 切换语言 - 使用全局函数
function changeLang(lang: string) {
  console.log('尝试切换语言到:', lang)
  if (availableLanguages.value.includes(lang)) {
    // 使用全局函数设置语言
    const success = setLocale(lang)
    console.log('语言切换结果:', success ? '成功' : '失败')
  } else {
    console.error('不支持的语言:', lang)
  }
}

// 切换语言
function changeLanguage(lang: string) {
  // eslint-disable-next-line no-console
  console.log(`切换语言到: ${lang}`)
  if (setLocale(lang)) {
    // 语言设置成功
    debugTranslation('title') // 调试翻译
  }
}

// 监听语言变更事件
function setupLocaleChangeListener() {
  window.addEventListener('locale-changed', (event) => {
    console.log('捕获到语言变更事件:', (event as CustomEvent).detail)
  })
}

onMounted(async () => {
  getUrlLanguage()
  setupLocaleChangeListener()

  // 打印调试信息
  console.log('当前语言:', currentLocale.value)
  console.log('可用语言列表:', availableLanguages.value)
  console.log('消息示例:', t('title'))
})

// 监听路由变化
watch(
  () => route.query,
  (query) => {
    const urlLang = query.lang as string
    if (urlLang && urlLang !== currentLang.value) {
      // eslint-disable-next-line no-console
      console.log(`路由变化,检测到语言参数: ${urlLang}`)
      changeLanguage(urlLang)
    }
    if (query.order_no) {
      getDetail(query.order_no as string)
    }
  }
)

async function getDetail(newOrderNo: string) {
  console.log('订单号:', newOrderNo)

  if (newOrderNo) {
    const res = await getOrderDetailApi(newOrderNo as string)
    if (res.data) {
      orderStore.fillFromOrderDetail(res.data)
      console.log('用户信息', orderStore.customer.mobile)
    }
  }
}
</script>

<style>
/* 应用程序样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

html,
body {
  height: 100%;
}

/* 调试面板样式 */
.debug-panel {
  position: fixed;
  top: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px;
  font-size: 12px;
  z-index: 9999;
  border-radius: 0 0 0 5px;
  max-width: 300px;
}

.debug-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  margin-top: 10px;
}

.debug-buttons button {
  background: #4285f4;
  color: white;
  border: none;
  padding: 5px;
  border-radius: 3px;
  cursor: pointer;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.language-switcher {
  position: fixed;
  top: 10px;
  right: 10px;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 10px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  min-width: 150px;
}

.language-title {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 8px;
  text-align: center;
}

.language-buttons {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.language-buttons button {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  background-color: #f0f0f0;
  cursor: pointer;
  font-size: 13px;
}

.language-buttons button.active {
  background-color: #69d100;
  color: white;
  font-weight: bold;
}
</style>
